How to execute bcrypt.compare inside Sequelize .then?












1















I'm trying to build a login page where I get the hashed password from mysql db using Sequelize and then calling bcrypt compare to dehash the password and compare it with the user's login input for authentication.



However, bcrypt compare is always executing slower than the return causing the value to always be "". I know this has to do with asynchronous behaviour but I don't know how to properly write this code to make it work.



     authenticate: (req, res) => {

let userDetails = req.query;

User.findOne({
where: {
username: userDetails.username
}
})
.then((user) => {
// How can I make this so, correctPassword() finishes
// and then the authenticated variable will be either false or true?

let authenticated = correctPassword(userDetails.password, user.password);
return authenticated;
})
.then((authenticated) => {
// right now authenticated is "" in client side console.

res.send(authenticated);
})
.catch((error) => {
console.log('there was an error: ', error);
});
}
}

const correctPassword = (enteredPassword, originalPassword) => {
return bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
return res;
});
}









share|improve this question



























    1















    I'm trying to build a login page where I get the hashed password from mysql db using Sequelize and then calling bcrypt compare to dehash the password and compare it with the user's login input for authentication.



    However, bcrypt compare is always executing slower than the return causing the value to always be "". I know this has to do with asynchronous behaviour but I don't know how to properly write this code to make it work.



         authenticate: (req, res) => {

    let userDetails = req.query;

    User.findOne({
    where: {
    username: userDetails.username
    }
    })
    .then((user) => {
    // How can I make this so, correctPassword() finishes
    // and then the authenticated variable will be either false or true?

    let authenticated = correctPassword(userDetails.password, user.password);
    return authenticated;
    })
    .then((authenticated) => {
    // right now authenticated is "" in client side console.

    res.send(authenticated);
    })
    .catch((error) => {
    console.log('there was an error: ', error);
    });
    }
    }

    const correctPassword = (enteredPassword, originalPassword) => {
    return bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
    return res;
    });
    }









    share|improve this question

























      1












      1








      1








      I'm trying to build a login page where I get the hashed password from mysql db using Sequelize and then calling bcrypt compare to dehash the password and compare it with the user's login input for authentication.



      However, bcrypt compare is always executing slower than the return causing the value to always be "". I know this has to do with asynchronous behaviour but I don't know how to properly write this code to make it work.



           authenticate: (req, res) => {

      let userDetails = req.query;

      User.findOne({
      where: {
      username: userDetails.username
      }
      })
      .then((user) => {
      // How can I make this so, correctPassword() finishes
      // and then the authenticated variable will be either false or true?

      let authenticated = correctPassword(userDetails.password, user.password);
      return authenticated;
      })
      .then((authenticated) => {
      // right now authenticated is "" in client side console.

      res.send(authenticated);
      })
      .catch((error) => {
      console.log('there was an error: ', error);
      });
      }
      }

      const correctPassword = (enteredPassword, originalPassword) => {
      return bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
      return res;
      });
      }









      share|improve this question














      I'm trying to build a login page where I get the hashed password from mysql db using Sequelize and then calling bcrypt compare to dehash the password and compare it with the user's login input for authentication.



      However, bcrypt compare is always executing slower than the return causing the value to always be "". I know this has to do with asynchronous behaviour but I don't know how to properly write this code to make it work.



           authenticate: (req, res) => {

      let userDetails = req.query;

      User.findOne({
      where: {
      username: userDetails.username
      }
      })
      .then((user) => {
      // How can I make this so, correctPassword() finishes
      // and then the authenticated variable will be either false or true?

      let authenticated = correctPassword(userDetails.password, user.password);
      return authenticated;
      })
      .then((authenticated) => {
      // right now authenticated is "" in client side console.

      res.send(authenticated);
      })
      .catch((error) => {
      console.log('there was an error: ', error);
      });
      }
      }

      const correctPassword = (enteredPassword, originalPassword) => {
      return bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
      return res;
      });
      }






      javascript node.js asynchronous sequelize.js bcrypt






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 27 '18 at 23:20









      aclspyaclspy

      293




      293
























          2 Answers
          2






          active

          oldest

          votes


















          1














          You're almost there. You correctly intuited that correctPassword executes asyncronously, though it is written as if it's syncronous.



          First off, let's make correctPassword a promise, so we can use async/await or call .then on it



          const correctPassword = (enteredPassword, originalPassword) => {
          return new Promise(resolve => {
          bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
          resolve(res)
          });
          })
          }


          Next, you have two approaches to ensure the order of operations in your code executes correctly:



          (Recommended) Use async/await syntax allowing us to write synchronous-looking code:



          authenticate: async (req, res) => {
          let userDetails = req.query;
          try {
          const user = await User.findOne({
          where: {
          username: userDetails.username
          }
          });

          const authenticated = await correctPassword(userDetails.password, user.password);

          res.send(authenticated);
          } catch(e) {
          res.status(400).send(e)
          }
          }


          Continue using promises:



          authenticate: (req, res) => {
          let userDetails = req.query;
          User.findOne({
          where: {
          username: userDetails.username
          }
          }).then(() => {
          correctPassword(userDetails.password, user.password)
          .then(authenticated => {
          res.send(authenticated)
          })
          .catch(e => {
          res.send(e)
          })
          })
          }





          share|improve this answer


























          • Thank you. This worked and I went with your recommendation in using async/await syntax. Can you briefly explain to me why you are recommending this method as to continuing using promises?

            – aclspy
            Nov 28 '18 at 2:14











          • It's more concise and clean, and allows us to avoid "callback hell" with promises. In the "promises" example, we already had to nest one promise. Let's imagine we had to call another promise inside of that one; the code would become much less readable. async/await allows us to write code that looks synchronous

            – mcranston18
            Nov 28 '18 at 14:05



















          0














          You can't assign async function to variable which is used by sync code later on. If you want to do sync function, you can use await/aync. But in here I recommend you use promise for compare function as well.



          User.findOne({
          where: {
          username: userDetails.username
          }
          })
          .then((user) => {
          return correctPassword(userDetails.password, user.password);
          })
          .then((authenticated) => {
          res.send(authenticated);
          })


          Bcrypt also supports promise.



          const correctPassword = (enteredPassword, originalPassword) => {
          return bcrypt.compare(enteredPassword, originalPassword).then((res) =>{
          return res;
          });
          }





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53509726%2fhow-to-execute-bcrypt-compare-inside-sequelize-then%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            You're almost there. You correctly intuited that correctPassword executes asyncronously, though it is written as if it's syncronous.



            First off, let's make correctPassword a promise, so we can use async/await or call .then on it



            const correctPassword = (enteredPassword, originalPassword) => {
            return new Promise(resolve => {
            bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
            resolve(res)
            });
            })
            }


            Next, you have two approaches to ensure the order of operations in your code executes correctly:



            (Recommended) Use async/await syntax allowing us to write synchronous-looking code:



            authenticate: async (req, res) => {
            let userDetails = req.query;
            try {
            const user = await User.findOne({
            where: {
            username: userDetails.username
            }
            });

            const authenticated = await correctPassword(userDetails.password, user.password);

            res.send(authenticated);
            } catch(e) {
            res.status(400).send(e)
            }
            }


            Continue using promises:



            authenticate: (req, res) => {
            let userDetails = req.query;
            User.findOne({
            where: {
            username: userDetails.username
            }
            }).then(() => {
            correctPassword(userDetails.password, user.password)
            .then(authenticated => {
            res.send(authenticated)
            })
            .catch(e => {
            res.send(e)
            })
            })
            }





            share|improve this answer


























            • Thank you. This worked and I went with your recommendation in using async/await syntax. Can you briefly explain to me why you are recommending this method as to continuing using promises?

              – aclspy
              Nov 28 '18 at 2:14











            • It's more concise and clean, and allows us to avoid "callback hell" with promises. In the "promises" example, we already had to nest one promise. Let's imagine we had to call another promise inside of that one; the code would become much less readable. async/await allows us to write code that looks synchronous

              – mcranston18
              Nov 28 '18 at 14:05
















            1














            You're almost there. You correctly intuited that correctPassword executes asyncronously, though it is written as if it's syncronous.



            First off, let's make correctPassword a promise, so we can use async/await or call .then on it



            const correctPassword = (enteredPassword, originalPassword) => {
            return new Promise(resolve => {
            bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
            resolve(res)
            });
            })
            }


            Next, you have two approaches to ensure the order of operations in your code executes correctly:



            (Recommended) Use async/await syntax allowing us to write synchronous-looking code:



            authenticate: async (req, res) => {
            let userDetails = req.query;
            try {
            const user = await User.findOne({
            where: {
            username: userDetails.username
            }
            });

            const authenticated = await correctPassword(userDetails.password, user.password);

            res.send(authenticated);
            } catch(e) {
            res.status(400).send(e)
            }
            }


            Continue using promises:



            authenticate: (req, res) => {
            let userDetails = req.query;
            User.findOne({
            where: {
            username: userDetails.username
            }
            }).then(() => {
            correctPassword(userDetails.password, user.password)
            .then(authenticated => {
            res.send(authenticated)
            })
            .catch(e => {
            res.send(e)
            })
            })
            }





            share|improve this answer


























            • Thank you. This worked and I went with your recommendation in using async/await syntax. Can you briefly explain to me why you are recommending this method as to continuing using promises?

              – aclspy
              Nov 28 '18 at 2:14











            • It's more concise and clean, and allows us to avoid "callback hell" with promises. In the "promises" example, we already had to nest one promise. Let's imagine we had to call another promise inside of that one; the code would become much less readable. async/await allows us to write code that looks synchronous

              – mcranston18
              Nov 28 '18 at 14:05














            1












            1








            1







            You're almost there. You correctly intuited that correctPassword executes asyncronously, though it is written as if it's syncronous.



            First off, let's make correctPassword a promise, so we can use async/await or call .then on it



            const correctPassword = (enteredPassword, originalPassword) => {
            return new Promise(resolve => {
            bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
            resolve(res)
            });
            })
            }


            Next, you have two approaches to ensure the order of operations in your code executes correctly:



            (Recommended) Use async/await syntax allowing us to write synchronous-looking code:



            authenticate: async (req, res) => {
            let userDetails = req.query;
            try {
            const user = await User.findOne({
            where: {
            username: userDetails.username
            }
            });

            const authenticated = await correctPassword(userDetails.password, user.password);

            res.send(authenticated);
            } catch(e) {
            res.status(400).send(e)
            }
            }


            Continue using promises:



            authenticate: (req, res) => {
            let userDetails = req.query;
            User.findOne({
            where: {
            username: userDetails.username
            }
            }).then(() => {
            correctPassword(userDetails.password, user.password)
            .then(authenticated => {
            res.send(authenticated)
            })
            .catch(e => {
            res.send(e)
            })
            })
            }





            share|improve this answer















            You're almost there. You correctly intuited that correctPassword executes asyncronously, though it is written as if it's syncronous.



            First off, let's make correctPassword a promise, so we can use async/await or call .then on it



            const correctPassword = (enteredPassword, originalPassword) => {
            return new Promise(resolve => {
            bcrypt.compare(enteredPassword, originalPassword, (err, res) =>{
            resolve(res)
            });
            })
            }


            Next, you have two approaches to ensure the order of operations in your code executes correctly:



            (Recommended) Use async/await syntax allowing us to write synchronous-looking code:



            authenticate: async (req, res) => {
            let userDetails = req.query;
            try {
            const user = await User.findOne({
            where: {
            username: userDetails.username
            }
            });

            const authenticated = await correctPassword(userDetails.password, user.password);

            res.send(authenticated);
            } catch(e) {
            res.status(400).send(e)
            }
            }


            Continue using promises:



            authenticate: (req, res) => {
            let userDetails = req.query;
            User.findOne({
            where: {
            username: userDetails.username
            }
            }).then(() => {
            correctPassword(userDetails.password, user.password)
            .then(authenticated => {
            res.send(authenticated)
            })
            .catch(e => {
            res.send(e)
            })
            })
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 28 '18 at 15:43

























            answered Nov 27 '18 at 23:26









            mcranston18mcranston18

            2,02021825




            2,02021825













            • Thank you. This worked and I went with your recommendation in using async/await syntax. Can you briefly explain to me why you are recommending this method as to continuing using promises?

              – aclspy
              Nov 28 '18 at 2:14











            • It's more concise and clean, and allows us to avoid "callback hell" with promises. In the "promises" example, we already had to nest one promise. Let's imagine we had to call another promise inside of that one; the code would become much less readable. async/await allows us to write code that looks synchronous

              – mcranston18
              Nov 28 '18 at 14:05



















            • Thank you. This worked and I went with your recommendation in using async/await syntax. Can you briefly explain to me why you are recommending this method as to continuing using promises?

              – aclspy
              Nov 28 '18 at 2:14











            • It's more concise and clean, and allows us to avoid "callback hell" with promises. In the "promises" example, we already had to nest one promise. Let's imagine we had to call another promise inside of that one; the code would become much less readable. async/await allows us to write code that looks synchronous

              – mcranston18
              Nov 28 '18 at 14:05

















            Thank you. This worked and I went with your recommendation in using async/await syntax. Can you briefly explain to me why you are recommending this method as to continuing using promises?

            – aclspy
            Nov 28 '18 at 2:14





            Thank you. This worked and I went with your recommendation in using async/await syntax. Can you briefly explain to me why you are recommending this method as to continuing using promises?

            – aclspy
            Nov 28 '18 at 2:14













            It's more concise and clean, and allows us to avoid "callback hell" with promises. In the "promises" example, we already had to nest one promise. Let's imagine we had to call another promise inside of that one; the code would become much less readable. async/await allows us to write code that looks synchronous

            – mcranston18
            Nov 28 '18 at 14:05





            It's more concise and clean, and allows us to avoid "callback hell" with promises. In the "promises" example, we already had to nest one promise. Let's imagine we had to call another promise inside of that one; the code would become much less readable. async/await allows us to write code that looks synchronous

            – mcranston18
            Nov 28 '18 at 14:05













            0














            You can't assign async function to variable which is used by sync code later on. If you want to do sync function, you can use await/aync. But in here I recommend you use promise for compare function as well.



            User.findOne({
            where: {
            username: userDetails.username
            }
            })
            .then((user) => {
            return correctPassword(userDetails.password, user.password);
            })
            .then((authenticated) => {
            res.send(authenticated);
            })


            Bcrypt also supports promise.



            const correctPassword = (enteredPassword, originalPassword) => {
            return bcrypt.compare(enteredPassword, originalPassword).then((res) =>{
            return res;
            });
            }





            share|improve this answer






























              0














              You can't assign async function to variable which is used by sync code later on. If you want to do sync function, you can use await/aync. But in here I recommend you use promise for compare function as well.



              User.findOne({
              where: {
              username: userDetails.username
              }
              })
              .then((user) => {
              return correctPassword(userDetails.password, user.password);
              })
              .then((authenticated) => {
              res.send(authenticated);
              })


              Bcrypt also supports promise.



              const correctPassword = (enteredPassword, originalPassword) => {
              return bcrypt.compare(enteredPassword, originalPassword).then((res) =>{
              return res;
              });
              }





              share|improve this answer




























                0












                0








                0







                You can't assign async function to variable which is used by sync code later on. If you want to do sync function, you can use await/aync. But in here I recommend you use promise for compare function as well.



                User.findOne({
                where: {
                username: userDetails.username
                }
                })
                .then((user) => {
                return correctPassword(userDetails.password, user.password);
                })
                .then((authenticated) => {
                res.send(authenticated);
                })


                Bcrypt also supports promise.



                const correctPassword = (enteredPassword, originalPassword) => {
                return bcrypt.compare(enteredPassword, originalPassword).then((res) =>{
                return res;
                });
                }





                share|improve this answer















                You can't assign async function to variable which is used by sync code later on. If you want to do sync function, you can use await/aync. But in here I recommend you use promise for compare function as well.



                User.findOne({
                where: {
                username: userDetails.username
                }
                })
                .then((user) => {
                return correctPassword(userDetails.password, user.password);
                })
                .then((authenticated) => {
                res.send(authenticated);
                })


                Bcrypt also supports promise.



                const correctPassword = (enteredPassword, originalPassword) => {
                return bcrypt.compare(enteredPassword, originalPassword).then((res) =>{
                return res;
                });
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 27 '18 at 23:38

























                answered Nov 27 '18 at 23:31









                TrmaPhiTrmaPhi

                104




                104






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53509726%2fhow-to-execute-bcrypt-compare-inside-sequelize-then%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                    Calculate evaluation metrics using cross_val_predict sklearn

                    Insert data from modal to MySQL (multiple modal on website)