2017-10-10 190 views
-2

我想哈希和鹽密碼,但我有很多錯誤! 該代碼有什麼問題,或者鍵入它的正確方法是什麼?哈希和鹽漬密碼字段

user.js的代碼

const mongoose = require('mongoose') 
const schema = mongoose.Schema 
const promise = require('bluebird') 
const bcrypt = promise.promisifyAll(require('bcrypt')) 

function hashPassword(user, option) { 
    const SALT_FACTOR = 8 

    if (!user.isModified('password')) { 
    return; 
    } 

    return bcrypt 
    .genSaltAsync(SALT_FACTOR) 
    .then(salt => bcrypt.hashAsync(user.password, salt, null)) 
    .then(hash => { 
     user.setDataValue('password', hash) 
    }) 
} 

// create schema and model 
const userSchema = new schema({ 

    email: { 
     type: String, 
     required: true, 
     unique: true 
    }, 
    password: { 
     type: String, 
     required: true 
    } 

}) 

userSchema.pre('create', function(next) { 
    hashPassword() 

}) 

userSchema.pre('update', function(next) { 
    hashPassword() 

}) 

userSchema.pre('save', function(next) { 
    hashPassword() 

}) 

const user = mongoose.model('user', userSchema) 

user.prototype.compairePassword = function (password) { 
    return bcrypt.compareAsync(password, this.password) 
} 

module.exports = user 

回答

0
const mongoose = require('mongoose') 
const schema = mongoose.Schema 
const promise = require('bluebird') 
const bcrypt = promise.promisifyAll(require('bcrypt')) 
const SALT_WORK_FACTOR = 10 

// create schema and model 
const userSchema = new schema({ 

    email: { 
     type: String, 
     required: true, 
     unique: true 
    }, 
    password: { 
     type: String, 
     required: true 
    } 

}) 

userSchema.pre('save', function(next) { 
    const user = this 

    // only hash the password if it has been modified (or is new) 
    if (!user.isModified('password')) return next() 

    // generate a salt 
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { 
     if (err) return next(err) 

     // hash the password using our new salt 
     bcrypt.hash(user.password, salt, function(err, hash) { 
      if (err) return next(err) 

      // override the cleartext password with the hashed one 
      user.password = hash 
      next() 
     }) 
    }) 
}) 

userSchema.methods.comparePassword = function(candidatePassword, cb) { 
    bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { 
     if (err) return cb(err); 
     cb(null, isMatch); 
    }) 
} 


const user = mongoose.model('user', userSchema) 

module.exports = user