Bookshelfjs + bcrypt hashPassword正在进行创建,但不是在更新时

时间:2017-01-20 02:46:19

标签: javascript node.js express bcrypt bookshelf.js

我在bookshelfjs中使用bcrypt哈希密码,当我在注册时进行插入查询时工作正常,但是当我尝试更新密码时它没有哈希密码。

model.js

var Bookshelf = require('../../db').bookshelf;
var bcrypt = require('bcrypt');
var Promise  = require('bluebird');

// Provider model
var User = Bookshelf.Model.extend({
    tableName: 'user_table',
    initialize: function() {
        this.on('creating', this.hashPassword, this);
    },
    hashPassword: function(model, attrs, options) {
        return new Promise(function(resolve, reject) {
            bcrypt.hash(model.attributes.password, 10, function(err, hash) {
                if( err ) reject(err);
                model.set('password', hash);
                resolve(hash); // data is created only after this occurs
            });
        });
    }
});
var Users =  Bookshelf.Collection.extend({
    model: User
});

module.exports = {
    User: User,
    Users: Users
};

service.js

var updateUser = function (object ,whereId, callback) {
    Model.User.forge({id: whereId})
        .fetch({require: true})
        .then(function (user) {
            user.save(object)
                .then(function () {
                    console.log(user);
                    return callback(null, user);
                })
                .catch(function (err) {
                    return callback(err, null);
                });
        })
        .catch(function (err) {
            return callback(err, null);
        });
};

var createUser = function (reqObject, callback) {
    Model.User.forge(reqObject)
        .save()
        .then(function (user) {
            return callback(null, user);
        })
        .catch(function (err) {
            return callback(err, null);
        });
};

更新数据时:

var dataToBeUpdated = {
                            password : req.body.password
                        };

1 个答案:

答案 0 :(得分:1)

在模型中用'保存'替换'创建'将完成工作

var User = Bookshelf.Model.extend({
    tableName: 'user_table',
    initialize: function() {
        this.on('saving', this.hashPassword, this);
    },
    hashPassword: function(model, attrs, options) {
        return new Promise(function(resolve, reject) {
            bcrypt.hash(model.attributes.password, 10, function(err, hash) {
                if( err ) reject(err);
                model.set('password', hash);
                resolve(hash); // data is created only after this occurs
            });
        });
    }
});

来源:http://wesleytsai.io/2015/07/28/bookshelf-bcrpyt-password-hashing/