Home > Enterprise >  bcrypt password is changing after a time
bcrypt password is changing after a time

Time:05-20

I have created a app similar to blog app. Users can registered and login logout. When User creates it's account than logout than s/he can login again with the same password. However, after a spesific time(I couldn't specify the time exactly but more than 1 day) when user try to login with the same password and username. Bcrypt returns false.

This is function when user try to login.

userSchema.statics.login = async function(username,password){


const user = await this.findOne({username})
if (user){
    const auth = await bcrypt.compare(password,user.password)
    console.log(auth)
    if (auth){
        return user
    }else{
        throw Error('Password is wrong.')
    }
}else{
    throw Error('Username doesn\'t exist.')
}}

This is the function when user registers.

userSchema.pre('save', async function(next){
const salt = await bcrypt.genSalt()
this.password = await bcrypt.hash(this.password,salt)
next()
})

CodePudding user response:

Not sure if this helps but this is how I use bcrypt to pre save the password and also when comparing passwords:

// hash the password before the user is saved
UserSchema.pre('save', function hashPassword(next) {
  // hash the password only if the password has been changed or user is new
  if (!this.isModified('password')) {
    next();
    return;
  }

  // generate the hash
  _hash(this.password, null, null, (err, hash) => {
    if (err) {
      next(err);
      return;
    }

    // change the password to the hashed version
    this.password = hash;
    next();
  });
});

// method to compare a given password with the database hash
UserSchema.methods.comparePassword = function comparePassword(password) {
  const data = compareSync(password, this.password);
  return data;
};

  • Related