tinaJohnny
tinaJohnny

Reputation: 173

Use bcrypt to store password takes no effect

I use mongodb to store my user table, and use bcrypt to store password. However , the stored password is all in real text. My node js code is below:

var mongoose = require('mongoose')
var bcrypt = require('bcrypt')
var SALT_WORK_FACTOR = 10

var UserSchema = new mongoose.Schema({
name:{
    type:String,
    required: true,
    unique: true
},
password: {
    type: String,
    required: true
}
meta: {
    createAt: {
        type: Date,
        default: Date.now()
    },
    updateAt: {
        type: Date,
        default: Date.now()
      }
  }
})
UserSchema.pre('save',function(next){
var user = this
if(this.isNew){
    this.meta.createAt = this.meta.updateAt = Date.now()
}
else{
    this.meta.updateAt = Date.now()
}

bcrypt.genSalt(SALT_WORK_FACTOR,function(err, salt){
    if(err) return next(err)
        console.log('salt'+salt)
        bcrypt.hash(user.password, salt, function(err, hash){
            console.log('hash'+hash)
            if(err) 
                return next(err)

            console.log('set user password' + hash)
            user.password = hash
            next()

        })
})

next()
})

after that , i use db.users.find() in my mongo terminal , all I see is the password stored in real text:

{ "_id" : ObjectId("54d2f5a4162a7335c0036cae"), "name" : "12", "password" : "12", "meta" : { "updateAt" : ISODate("2015-02-05T04:46:28.246Z"), "createAt" : ISODate("2015-02-05T04:46:28.246Z") }, "__v" : 0 }

{ "_id" : ObjectId("54d2f89c0675b329c3e783d4"), "name" : "34", "password" : "34", "meta" : { "updateAt" : ISODate("2015-02-05T04:59:08.285Z"), "createAt" : ISODate("2015-02-05T04:59:08.285Z") }, "__v" : 0 }

{ "_id" : ObjectId("54d2f9703b55cdf5c32af5b2"), "name" : "457", "password" : "457", "meta" : { "updateAt" : ISODate("2015-02-05T05:03:23.338Z"), "createAt" : ISODate("2015-02-05T05:03:23.338Z") }, "__v" : 0 }

and because of that , my compare function always return false:

UserSchema.methods = {
comparePassword: function(_password, cb){
    bcrypt.compare(_password, this.password, function(err, isMatched){
        if(err) 
            return cb(err)

        cb(null, isMatched)
    })
}
}

Could somebody help me solve this?

Upvotes: 0

Views: 150

Answers (1)

mscdex
mscdex

Reputation: 106696

My guess is that because you have an extra next() immediately after your call to bcrypt.genSalt(), the value of user.password hasn't changed before the entry is saved to the database. So remove the next() immediately after bcrypt.genSalt() and it should work as expected.

Upvotes: 1

Related Questions