Struggling to securely post data to an Express server by hashing passwords with bcrypt?

I'm currently working on developing an API using Express and Sequelize. Specifically, I am writing a function to create a new user where I utilize bcrypt for password hashing.

 const createNewUser = (data) => {
  return new Promise(async (resolve, reject) => {
    try {
      let check = await checkUserEmail(data.email)
      if (check === true) {
        resolve({
          errcode: 1,
          errMessage: 'Your email is already exist!',
        })
      }
      let hashPassWordFromBcrypt = await hashUserPassWord(data.passWord)
  

      await db.User.create({
        email: data.email,
        passWord: hashPassWordFromBcrypt,
        firstName: data.firstName,
        lastName: data.lastName,
        address: data.address,
        phoneNumber: data.phoneNumber,
        gender: data.gender === '1' ? true : false,
        roleId: data.roleId,
      })
     resolve({
       errcode: 0,
       errMessage: 'OK',
     })
} catch (error) {
  reject(error)
}

}) }

const salt = bcrypt.genSaltSync(10)

const hashUserPassWord = (password) => {
  return new Promise(async (resolve, reject) => {
    try {
      let hashPassWord = await bcrypt.hashSync(password, salt)
      resolve(hashPassWord)
    } catch (error) {
      reject(error)
    }
  })
}

const checkUserEmail = (email) => {
  return new Promise(async (resolve, reject) => {
    try {
      const user = await db.User.findOne({ where: { email } })
      if (user) {
        resolve(true)
      }
      resolve(false)
    } catch (e) {
      reject(e)
    }
  })
}

While testing with Postman, I encountered a problem. When sending data with an email that already exists, the response shows errCode: 1 and

errMessage: Your email is already exist
, but a new user is still created with the same email. However, when posting a request with an already existing email and without a password, no new user is created. I need assistance to rectify this issue. Thank you!

Answer №1

When using a resolve or reject statement within a promise executor function, it's important to note that these statements do not exit the function. Here is an example:

if (check === true) {
  return resolve({
    errcode: 1,
    errMessage: 'Your email is already exist!',
  })
}

If the condition is not met, the db.User.create operation will be executed next.

In your code snippet:

if (user) {
  resolve(true)
}
resolve(false)

It may appear that the resolve statement exits the function, but in reality, it does not. Keep in mind that in this specific scenario, calling resolve(false) after resolving to true has no impact on the outcome of the promise.

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

Middleware functions in Mongoose for pre and post actions are not being triggered when attempting to save

After carefully reviewing the documentation, I am still unable to pinpoint the issue. The pre & post middleware functions do not appear to be functioning as expected. I have made sure to update both my node version and all modules. // schema.js const sch ...

Can you explain the function of MathUtils.euclideanModulo and how it sets itself apart from the traditional modulo operation?

I'm a little puzzled by the euclideanModulo function in threejs's mathutils. I understand the concept of the modulo operator, but the euclideanModulo function seems to work differently. ( ( n % m ) + m ) % m I tried researching the meaning of "E ...

Struggling to make the upvoting feature function properly in the Thinkster MEAN Stack Tutorial

While following the MEAN Stack tutorial on this website, I decided to modify my code to utilize Controller as instead of using $scope as demonstrated in their examples. I am encountering an issue with the upvote functionality. Whenever I click to upvote a ...

What are the steps to run a webpack project without relying on webpack-dev-server?

I've been working on hosting my project on GitHub pages by creating a /doc file and placing all my HTML, CSS, and JS there. If you're interested, you can check out my project here: https://github.com/mattfrancis888/the_movie_db The only way I&a ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

Issues with Node's Async/Await feature are preventing proper functionality, prompting the need for callback implementation

Take a look at my controller: exports.userList = async (req, res) => { let result = await Methods.getAllData(Campaign) await console.log(result, 'tr') } In this code snippet, Methods.getAllData is a function designed to retrieve all us ...

The `user-select: none` property displays distinct behavior in Safari

My Goal I am in the process of creating an input-like content editable div. The idea is to click on tags outside the div and insert them inside the div while still being able to type around these tags. The Issue and Reproduction Steps To prevent tag but ...

What is the best way to customize the interval time for my specific situation?

I'm working on setting an interval in my app and I have the following code: HTML <div class="text"> {{currentItem.name}} </div> <ul> <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li> ...

Display some results at the conclusion of eslint processing

As I develop a custom eslint plugin, I am intricately analyzing every MemberExpression to gather important data. Once all the expressions have been processed, I want to present a summary based on this data. Is there a specific event in eslint, such as "a ...

Navigate to a specified div using JavaScript

I'm having an issue with my navigation bar not scrolling to the designated div. Despite looking at other examples, I can't seem to find a solution <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

The combination of Fabric.js, Darkroom.js, and devicePixelRatio offset creates a powerful tool

Having reached out on the Darkroom.js GitHub page with little activity, I'm turning to this platform for assistance. Despite being a great plugin overall, I've run into some issues while testing it on a Retina screen. Everything works fine on a ...

loading xml data into a table partially using jquery

Currently, I am utilizing AJAX to load and parse XML data. I have constructed a table where I am inserting the data from the XML using a loop. The issue lies in the fact that only around 3000 rows are being inserted into the table even though the XML conta ...

Is getElementById() returning null?

I'm currently working on a JavaScript program that takes an image URL and displays it on the page by creating an <img> tag. This way, I can easily add multiple images to the page. Here is my code: <!DOCTYPE html> <html lang="en&quo ...

Creating PopUp Windows with PHP and JavaScript

There is a function created on my page that opens a pop-up window when clicking on a game-mod name: <SCRIPT language="javascript" type="text/javascript"> function popModData( modName ) { var url = "./modList.php?mod=" + modName; ...

Changing the event when a class is active in Vue3

Question I am looking for a way to trigger an event when the 'active' class is added to an element. How can I achieve this? I believe this could potentially be accomplished using a watcher method, but I am unsure how to watch for the applicatio ...

The creation of the ESLint CLIEngine encountered some issues

Encountered an issue while setting up the ESLint CLIEngine - 'basePath' must be an absolute path Attempting to utilize eslint $ npx prettier-eslint **/*.js However, receiving the following error message: prettier-eslint [ERROR]: Encountered a ...

Step-by-step guide to launching a new window or tab without automatically bringing it into focus

Is it possible to use JavaScript to open a URL in a new tab without giving that tab focus on a click event? ...

Can you explain the contrast between window.performance and PerformanceObserver?

As I delve into exploring the performance APIs, I have come across window.performance and PerformanceObserver. These two functionalities seem to serve similar purposes. For instance, if I need to obtain the FCP time, I can retrieve it from performance.getE ...

Trouble accessing contacts on LinkedIn

When attempting to retrieve the LinkedIn connections for a logged-in user, I used the following API Request: However, I encountered an error message: { "errorCode": 0, "message": "Access to connections denied", "requestId": "OFP0JOLOHO", "status" ...