How to embed bcrypt into mongose API call?Laravel 5: using bcrypt on same string gives different valuesMongoose: findOneAndUpdate pre hook not workingMongoose MODEL update() vs save()How to generate a random string in RubyDo I need to store the salt with bcrypt?What is the best Distributed Brute Force countermeasure?SHA512 vs. Blowfish and BcryptHow do you use bcrypt for hashing passwords in PHP?How can bcrypt have built-in salts?How can we authenticate with JAAS using a file with Bcrypt passwords as authentication source?Migrate user authentication to Firebase AuthShould I refresh access token on API

Is it acceptable that I plot a time-series figure with years increasing from right to left?

How do I check that users don't write down their passwords?

When is one 'Ready' to make Original Contributions to Mathematics?

I'm feeling like my character doesn't fit the campaign

How to deal with a Murder Hobo Paladin?

Why did Super-VGA offer the 5:4 1280*1024 resolution?

What are some bad ways to subvert tropes?

What do I need to see before Spider-Man: Far From Home?

How can I use my cell phone's light as a reading light?

Machine Learning Golf: Multiplication

Park the computer

Do I need transit visa for Dublin?

Why do Martians have to wear space helmets?

Can you take the Dodge action while prone?

Are "confidant" and "confident" homophones?

Is reasonable to assume that the 食 in 月食/日食 can be interpreted as the sun/moon being "eaten" during an eclipse?

Who goes first? Person disembarking bus or the bicycle?

In the Seventh Seal why does Death let the chess game happen?

Do intermediate subdomains need to exist?

Why does this function pointer assignment work when assigned directly but not with the conditional operator?

How would a sea turtle end up on its back?

Soda water first stored in refrigerator and then outside

How did the IEC decide to create kibibytes?

Will Jimmy fall off his platform?



How to embed bcrypt into mongose API call?


Laravel 5: using bcrypt on same string gives different valuesMongoose: findOneAndUpdate pre hook not workingMongoose MODEL update() vs save()How to generate a random string in RubyDo I need to store the salt with bcrypt?What is the best Distributed Brute Force countermeasure?SHA512 vs. Blowfish and BcryptHow do you use bcrypt for hashing passwords in PHP?How can bcrypt have built-in salts?How can we authenticate with JAAS using a file with Bcrypt passwords as authentication source?Migrate user authentication to Firebase AuthShould I refresh access token on API






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Setup



I am doing web site authorization, and want to embed best practices into it, while keeping code clean and readible. For now I have classic code like this:



let foundUser = await userModel.findOne( email: recievedEmail );
if(!foundUser)
error("not authorized!");
const isPasswordMatch = await bcrypt.compare(recievedPassword, foundUser.password);
if(!isPasswordMatch)
error("not authorized!");
foundUser.update( $set: lastLogin: new Date() , $push: myEvents: authEvent );
foundUser.save();
success("authorized OK!");


Meanwhile, I've asked a question on the best mongoose command to perform auth, and we've forged up the following "auth-check-and-update" command, in an "atomic" manner:



const foundUser = await userModel.findOneAndUpdate(
email: recievedEmail, password: recievedPassword ,
$set: lastLogin: new Date() , $push: myEvents: authEvent
);
if(foundUser)
success("authorized OK!");
else
error("not authorized!");


Idea here is obvious - if a user with matching email and password is found then user is considered as authorized, and its last login timestamp is updated (simultaneously).




Problem



To combine best practices from the two above, I need somehow to embed bcrypt.compare() call inside findOneAndUpdate() call. That is tricky to do, because I cannot just "compare hashed passwords"; bcrypt just works differently from simple hashes (like sha or md5): For security reasons it returns different hashes every time. (Answers in the link explains "why and how").




Solution Attempt



I've looked into mongoose-bcrypt package: it is utilizing Schema.pre() functionality:



 schema.pre('update', preUpdate);
schema.pre('findOneAndUpdate', preUpdate);


To get the idea, please, take a look at mongoose-bcryptindex.js.
You will see, that preUpdate affects only creating new user (..andUpdate part), but not actual checking (findOne.. part). So this plugin could fit for implementing "user registration" / "change password". But it can't work for authorization in the proposed way.




Question



How would you "combine" bcrypt.compare() and userModel.findOneAndUpdate() calls under such circumstances?










share|improve this question






























    0















    Setup



    I am doing web site authorization, and want to embed best practices into it, while keeping code clean and readible. For now I have classic code like this:



    let foundUser = await userModel.findOne( email: recievedEmail );
    if(!foundUser)
    error("not authorized!");
    const isPasswordMatch = await bcrypt.compare(recievedPassword, foundUser.password);
    if(!isPasswordMatch)
    error("not authorized!");
    foundUser.update( $set: lastLogin: new Date() , $push: myEvents: authEvent );
    foundUser.save();
    success("authorized OK!");


    Meanwhile, I've asked a question on the best mongoose command to perform auth, and we've forged up the following "auth-check-and-update" command, in an "atomic" manner:



    const foundUser = await userModel.findOneAndUpdate(
    email: recievedEmail, password: recievedPassword ,
    $set: lastLogin: new Date() , $push: myEvents: authEvent
    );
    if(foundUser)
    success("authorized OK!");
    else
    error("not authorized!");


    Idea here is obvious - if a user with matching email and password is found then user is considered as authorized, and its last login timestamp is updated (simultaneously).




    Problem



    To combine best practices from the two above, I need somehow to embed bcrypt.compare() call inside findOneAndUpdate() call. That is tricky to do, because I cannot just "compare hashed passwords"; bcrypt just works differently from simple hashes (like sha or md5): For security reasons it returns different hashes every time. (Answers in the link explains "why and how").




    Solution Attempt



    I've looked into mongoose-bcrypt package: it is utilizing Schema.pre() functionality:



     schema.pre('update', preUpdate);
    schema.pre('findOneAndUpdate', preUpdate);


    To get the idea, please, take a look at mongoose-bcryptindex.js.
    You will see, that preUpdate affects only creating new user (..andUpdate part), but not actual checking (findOne.. part). So this plugin could fit for implementing "user registration" / "change password". But it can't work for authorization in the proposed way.




    Question



    How would you "combine" bcrypt.compare() and userModel.findOneAndUpdate() calls under such circumstances?










    share|improve this question


























      0












      0








      0








      Setup



      I am doing web site authorization, and want to embed best practices into it, while keeping code clean and readible. For now I have classic code like this:



      let foundUser = await userModel.findOne( email: recievedEmail );
      if(!foundUser)
      error("not authorized!");
      const isPasswordMatch = await bcrypt.compare(recievedPassword, foundUser.password);
      if(!isPasswordMatch)
      error("not authorized!");
      foundUser.update( $set: lastLogin: new Date() , $push: myEvents: authEvent );
      foundUser.save();
      success("authorized OK!");


      Meanwhile, I've asked a question on the best mongoose command to perform auth, and we've forged up the following "auth-check-and-update" command, in an "atomic" manner:



      const foundUser = await userModel.findOneAndUpdate(
      email: recievedEmail, password: recievedPassword ,
      $set: lastLogin: new Date() , $push: myEvents: authEvent
      );
      if(foundUser)
      success("authorized OK!");
      else
      error("not authorized!");


      Idea here is obvious - if a user with matching email and password is found then user is considered as authorized, and its last login timestamp is updated (simultaneously).




      Problem



      To combine best practices from the two above, I need somehow to embed bcrypt.compare() call inside findOneAndUpdate() call. That is tricky to do, because I cannot just "compare hashed passwords"; bcrypt just works differently from simple hashes (like sha or md5): For security reasons it returns different hashes every time. (Answers in the link explains "why and how").




      Solution Attempt



      I've looked into mongoose-bcrypt package: it is utilizing Schema.pre() functionality:



       schema.pre('update', preUpdate);
      schema.pre('findOneAndUpdate', preUpdate);


      To get the idea, please, take a look at mongoose-bcryptindex.js.
      You will see, that preUpdate affects only creating new user (..andUpdate part), but not actual checking (findOne.. part). So this plugin could fit for implementing "user registration" / "change password". But it can't work for authorization in the proposed way.




      Question



      How would you "combine" bcrypt.compare() and userModel.findOneAndUpdate() calls under such circumstances?










      share|improve this question
















      Setup



      I am doing web site authorization, and want to embed best practices into it, while keeping code clean and readible. For now I have classic code like this:



      let foundUser = await userModel.findOne( email: recievedEmail );
      if(!foundUser)
      error("not authorized!");
      const isPasswordMatch = await bcrypt.compare(recievedPassword, foundUser.password);
      if(!isPasswordMatch)
      error("not authorized!");
      foundUser.update( $set: lastLogin: new Date() , $push: myEvents: authEvent );
      foundUser.save();
      success("authorized OK!");


      Meanwhile, I've asked a question on the best mongoose command to perform auth, and we've forged up the following "auth-check-and-update" command, in an "atomic" manner:



      const foundUser = await userModel.findOneAndUpdate(
      email: recievedEmail, password: recievedPassword ,
      $set: lastLogin: new Date() , $push: myEvents: authEvent
      );
      if(foundUser)
      success("authorized OK!");
      else
      error("not authorized!");


      Idea here is obvious - if a user with matching email and password is found then user is considered as authorized, and its last login timestamp is updated (simultaneously).




      Problem



      To combine best practices from the two above, I need somehow to embed bcrypt.compare() call inside findOneAndUpdate() call. That is tricky to do, because I cannot just "compare hashed passwords"; bcrypt just works differently from simple hashes (like sha or md5): For security reasons it returns different hashes every time. (Answers in the link explains "why and how").




      Solution Attempt



      I've looked into mongoose-bcrypt package: it is utilizing Schema.pre() functionality:



       schema.pre('update', preUpdate);
      schema.pre('findOneAndUpdate', preUpdate);


      To get the idea, please, take a look at mongoose-bcryptindex.js.
      You will see, that preUpdate affects only creating new user (..andUpdate part), but not actual checking (findOne.. part). So this plugin could fit for implementing "user registration" / "change password". But it can't work for authorization in the proposed way.




      Question



      How would you "combine" bcrypt.compare() and userModel.findOneAndUpdate() calls under such circumstances?







      authentication mongoose passwords mongoose-schema bcrypt






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 26 at 13:59







      xakepp35

















      asked Mar 22 at 18:26









      xakepp35xakepp35

      9126 silver badges24 bronze badges




      9126 silver badges24 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          1














          What about compare password in UserModel like this



          // method to compare password input to password saved in database
          UserModel.methods.isValidPassword = async function(password)
          const user = this;
          const compare = await bcrypt.compare(password, user.password);
          return compare;



          And inside your auth or passport (i am using passport) do something like this



          passport.use(new LocalStrategy(
          (username, password, done) =>
          // change your query here with findOneAndUpdate
          User.findOne( username: username , (err, user) =>
          if (err) return done(err);
          if (!user)

          return done(null, false, message: 'Incorrect username.' );

          if (!user.isValidPassword(password))

          return done(null, false, message: 'Incorrect password.' );

          return done(null, user);
          );

          ));





          share|improve this answer























          • You shound not call isValidPassword, because you must check user password only inside findOneAndUpdate: if a user is returned then its name and pasword alredy matched! Checking before call is too early. checking after call is too late. How to check bcrypted password just inside findOneAndUpdate?

            – xakepp35
            Mar 25 at 22:20












          • That is a bit advanced question, sorry I formed it badly. (I alredy have a working authorisation code, similar to that you wrote)

            – xakepp35
            Mar 25 at 22:24












          • I've edited question to better fit what exactly I wanted.

            – xakepp35
            Mar 25 at 22:37











          • what about this: stackoverflow.com/questions/52482992/…

            – Zombie
            Mar 28 at 10:52











          • This calls bcrypt.hash() but I need bcrypt.compare ()

            – xakepp35
            Mar 28 at 11:02










          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%2f55305780%2fhow-to-embed-bcrypt-into-mongose-api-call%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          What about compare password in UserModel like this



          // method to compare password input to password saved in database
          UserModel.methods.isValidPassword = async function(password)
          const user = this;
          const compare = await bcrypt.compare(password, user.password);
          return compare;



          And inside your auth or passport (i am using passport) do something like this



          passport.use(new LocalStrategy(
          (username, password, done) =>
          // change your query here with findOneAndUpdate
          User.findOne( username: username , (err, user) =>
          if (err) return done(err);
          if (!user)

          return done(null, false, message: 'Incorrect username.' );

          if (!user.isValidPassword(password))

          return done(null, false, message: 'Incorrect password.' );

          return done(null, user);
          );

          ));





          share|improve this answer























          • You shound not call isValidPassword, because you must check user password only inside findOneAndUpdate: if a user is returned then its name and pasword alredy matched! Checking before call is too early. checking after call is too late. How to check bcrypted password just inside findOneAndUpdate?

            – xakepp35
            Mar 25 at 22:20












          • That is a bit advanced question, sorry I formed it badly. (I alredy have a working authorisation code, similar to that you wrote)

            – xakepp35
            Mar 25 at 22:24












          • I've edited question to better fit what exactly I wanted.

            – xakepp35
            Mar 25 at 22:37











          • what about this: stackoverflow.com/questions/52482992/…

            – Zombie
            Mar 28 at 10:52











          • This calls bcrypt.hash() but I need bcrypt.compare ()

            – xakepp35
            Mar 28 at 11:02















          1














          What about compare password in UserModel like this



          // method to compare password input to password saved in database
          UserModel.methods.isValidPassword = async function(password)
          const user = this;
          const compare = await bcrypt.compare(password, user.password);
          return compare;



          And inside your auth or passport (i am using passport) do something like this



          passport.use(new LocalStrategy(
          (username, password, done) =>
          // change your query here with findOneAndUpdate
          User.findOne( username: username , (err, user) =>
          if (err) return done(err);
          if (!user)

          return done(null, false, message: 'Incorrect username.' );

          if (!user.isValidPassword(password))

          return done(null, false, message: 'Incorrect password.' );

          return done(null, user);
          );

          ));





          share|improve this answer























          • You shound not call isValidPassword, because you must check user password only inside findOneAndUpdate: if a user is returned then its name and pasword alredy matched! Checking before call is too early. checking after call is too late. How to check bcrypted password just inside findOneAndUpdate?

            – xakepp35
            Mar 25 at 22:20












          • That is a bit advanced question, sorry I formed it badly. (I alredy have a working authorisation code, similar to that you wrote)

            – xakepp35
            Mar 25 at 22:24












          • I've edited question to better fit what exactly I wanted.

            – xakepp35
            Mar 25 at 22:37











          • what about this: stackoverflow.com/questions/52482992/…

            – Zombie
            Mar 28 at 10:52











          • This calls bcrypt.hash() but I need bcrypt.compare ()

            – xakepp35
            Mar 28 at 11:02













          1












          1








          1







          What about compare password in UserModel like this



          // method to compare password input to password saved in database
          UserModel.methods.isValidPassword = async function(password)
          const user = this;
          const compare = await bcrypt.compare(password, user.password);
          return compare;



          And inside your auth or passport (i am using passport) do something like this



          passport.use(new LocalStrategy(
          (username, password, done) =>
          // change your query here with findOneAndUpdate
          User.findOne( username: username , (err, user) =>
          if (err) return done(err);
          if (!user)

          return done(null, false, message: 'Incorrect username.' );

          if (!user.isValidPassword(password))

          return done(null, false, message: 'Incorrect password.' );

          return done(null, user);
          );

          ));





          share|improve this answer













          What about compare password in UserModel like this



          // method to compare password input to password saved in database
          UserModel.methods.isValidPassword = async function(password)
          const user = this;
          const compare = await bcrypt.compare(password, user.password);
          return compare;



          And inside your auth or passport (i am using passport) do something like this



          passport.use(new LocalStrategy(
          (username, password, done) =>
          // change your query here with findOneAndUpdate
          User.findOne( username: username , (err, user) =>
          if (err) return done(err);
          if (!user)

          return done(null, false, message: 'Incorrect username.' );

          if (!user.isValidPassword(password))

          return done(null, false, message: 'Incorrect password.' );

          return done(null, user);
          );

          ));






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 25 at 20:28









          ZombieZombie

          1,0849 silver badges17 bronze badges




          1,0849 silver badges17 bronze badges












          • You shound not call isValidPassword, because you must check user password only inside findOneAndUpdate: if a user is returned then its name and pasword alredy matched! Checking before call is too early. checking after call is too late. How to check bcrypted password just inside findOneAndUpdate?

            – xakepp35
            Mar 25 at 22:20












          • That is a bit advanced question, sorry I formed it badly. (I alredy have a working authorisation code, similar to that you wrote)

            – xakepp35
            Mar 25 at 22:24












          • I've edited question to better fit what exactly I wanted.

            – xakepp35
            Mar 25 at 22:37











          • what about this: stackoverflow.com/questions/52482992/…

            – Zombie
            Mar 28 at 10:52











          • This calls bcrypt.hash() but I need bcrypt.compare ()

            – xakepp35
            Mar 28 at 11:02

















          • You shound not call isValidPassword, because you must check user password only inside findOneAndUpdate: if a user is returned then its name and pasword alredy matched! Checking before call is too early. checking after call is too late. How to check bcrypted password just inside findOneAndUpdate?

            – xakepp35
            Mar 25 at 22:20












          • That is a bit advanced question, sorry I formed it badly. (I alredy have a working authorisation code, similar to that you wrote)

            – xakepp35
            Mar 25 at 22:24












          • I've edited question to better fit what exactly I wanted.

            – xakepp35
            Mar 25 at 22:37











          • what about this: stackoverflow.com/questions/52482992/…

            – Zombie
            Mar 28 at 10:52











          • This calls bcrypt.hash() but I need bcrypt.compare ()

            – xakepp35
            Mar 28 at 11:02
















          You shound not call isValidPassword, because you must check user password only inside findOneAndUpdate: if a user is returned then its name and pasword alredy matched! Checking before call is too early. checking after call is too late. How to check bcrypted password just inside findOneAndUpdate?

          – xakepp35
          Mar 25 at 22:20






          You shound not call isValidPassword, because you must check user password only inside findOneAndUpdate: if a user is returned then its name and pasword alredy matched! Checking before call is too early. checking after call is too late. How to check bcrypted password just inside findOneAndUpdate?

          – xakepp35
          Mar 25 at 22:20














          That is a bit advanced question, sorry I formed it badly. (I alredy have a working authorisation code, similar to that you wrote)

          – xakepp35
          Mar 25 at 22:24






          That is a bit advanced question, sorry I formed it badly. (I alredy have a working authorisation code, similar to that you wrote)

          – xakepp35
          Mar 25 at 22:24














          I've edited question to better fit what exactly I wanted.

          – xakepp35
          Mar 25 at 22:37





          I've edited question to better fit what exactly I wanted.

          – xakepp35
          Mar 25 at 22:37













          what about this: stackoverflow.com/questions/52482992/…

          – Zombie
          Mar 28 at 10:52





          what about this: stackoverflow.com/questions/52482992/…

          – Zombie
          Mar 28 at 10:52













          This calls bcrypt.hash() but I need bcrypt.compare ()

          – xakepp35
          Mar 28 at 11:02





          This calls bcrypt.hash() but I need bcrypt.compare ()

          – xakepp35
          Mar 28 at 11:02








          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







          Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















          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%2f55305780%2fhow-to-embed-bcrypt-into-mongose-api-call%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript