2015-08-23 21 views
5

Tôi muốn lưu mật khẩu được băm. Tôi đang sử dụng setterMethod cho điều này:Làm thế nào tôi có thể chạy xác thực mô hình trước khi setterMethod trong Sequelize?

module.exports = (sequelize, DataTypes) -> 
    sequelize.define 'User', 
    # other model fields [...] 
    password: 
     type: DataTypes.STRING 
     validate: notEmpty: msg: 'You need to set a password.' 
     set: (pw) -> 
     salt = bcrypt.genSaltSync(10) 
     hash = bcrypt.hashSync(pw, salt) 
     @setDataValue('password', hash) 

Bộ cài đặt chạy trước. Mật khẩu chuỗi trống ('') được băm thành mật khẩu không trống (ví dụ: $2a$10$pDDIGnV.r47i9YOv0Fls/euQ0yYvfyq8T1SyP9VRQsTUAqptNmxXO).

Khi trình xác thực xác thực, mật khẩu không còn trống nữa.

Tôi làm cách nào để xác thực mật khẩu trước khi thiết lập?

Tôi đã xem xét hooks nhưng họ cũng không đề cập đến người định cư.

Tôi đang sử dụng [email protected]2.1.3.

Trả lời

0

Tôi giải quyết vấn đề này bằng cách sử dụng hai trường, một là loại VIRTUAL xử lý đầu vào và xác thực, và một loại là STRING chứa mật khẩu được băm.

Ví dụ này không phải là coffeescript nhưng bạn sẽ có thể dịch dễ dàng.

password_hash: { 
    type: DatabaseTypes.STRING, 
    allowNull: false, 
    validate: { 
    notEmpty: true, 
    }, 
}, 
password: { 
    type: DatabaseTypes.VIRTUAL, 
    allowNull: false, 
    // note that arrow functions cannot access "this", so use the form: 
    set: function setPassword(val) { 
    // trigger validation on "password" field 
    this.setDataValue('password', val); 

    // hash the password, this can be done in one step by passing the 
    // number of salt rounds instead of the salt string. 
    this.setDataValue('password_hash', bcrypt.hashSync(val, 10)); 
    }, 
    validate: { 
    notEmpty: { 
     message: 'You need to set a password.', 
    }, 
    }, 
}, 

Khi bạn xác thực người dùng so sánh mật khẩu nhập vào User.password_hash hơn User.password.

instanceMethods: { 
    // authenticate user given a password 
    authenticate(password) { 
    return bcrypt.compareSync(password, this.password_hash); 
    }, 
}, 

Sau đó, bạn có thể gọi phương thức thể hiện này để xác thực User.

User.findById(userId) 
.then((user) => { 
    if (user.authenticate(password)) { 
    console.log('Authenticated'); 
    } else { 
    console.log('Not authenticated'); 
    } 
}); 
Các vấn đề liên quan