2017-05-12 81 views
1

對於一個項目,我需要用戶,我想在數據庫中存儲加密的密碼。Sails.js - 加密密碼

所以我需要你的幫助,因爲我需要我的時候添加一個用戶加密密碼,但我有一個錯誤到終端時我啓動sails lift

In model `user`: 
The `toJSON` instance method is no longer supported. 
Instead, please use the `customToJSON` model setting. 

配置:

我使用Sails 1.0 BetaBcrypt 1.0.2

型號user.js的

/** 
* User.js 
* 
* @description :: A model definition. Represents a database 
table/collection/etc. 
* @docs  :: https://sailsjs.com/docs/concepts/models-and- 
orm/models 
*/ 

var bcrypt = require('bcrypt'); 


module.exports = { 


attributes: { 
    firstname: { 
     type: 'string' 
    }, 
    lastname: { 
     type: 'string' 
    }, 
    password: { 
     type: 'string' 
    }, 
    email: { 
     type: 'string', 
     unique: true 
    }, 
    code: { 
     type: 'string', 
     unique: true 
    }, 
    referring: { 
     type: 'string' 
    }, 
    comment: { 
     type: 'text' 
    }, 
    // Add reference to Profil 
    profil: { 
     model: 'profil' 
    }, 
    toJSON: function() { 
     var obj = this.toObject(); 
     delete obj.password; 
     return obj; 
    } 
}, 
beforeCreate: function(user, cb) { 
    bcrypt.genSalt(10, function(err, salt) { 
     bcrypt.hash(user.password, salt, function(err, hash) { 
      if (err) { 
       console.log(err); 
       cb(err); 
      } else { 
       user.password = hash; 
       cb(); 
      } 
     }); 
    }); 
} 
}; 

我想我使用的是舊的方式來加密密碼,但我不知道或不找到另一種方式來做到這一點。

在此先感謝

+0

'bcrypt'是不加密的,它只是嚴重命名。它是密碼哈希方法,設計用於包含大量CPU計算時間的密碼,這是一種安全的方法。關鍵是要讓攻擊者花費大量時間通過強力查找密碼。 – zaph

回答

0

您看到的錯誤與加密無關。看看你的模型,並注意toJSON函數。如錯誤消息所示,這是一種實例方法,不再受支持。建議如下:使用customToJSON模型設置。我相信你會在文檔中找到它。

0

我知道這個問題已經很老了,但是很快地,這會給我們一些啓示。

從Sails 1.0開始,不再支持實例方法。該文檔建議您應該使用customToJSON來代替,但它沒有說明您應該在屬性之外使用它。

customToJSON允許您在發送數據之前使用自定義函數對數據進行串聯。 在你的情況下,你會想要省略密碼。 使用customToJSON,您可以使用this關鍵字來訪問返回的對象。建議不要改變這個對象,intsead創建一個副本。

因此,對於你的榜樣,你會使用:

module.exports = { 

    attributes: {...}, 

    customToJSON: function() { 
    return _.omit(this, ['password']) 
    }, 

    beforeCreate: function(user, cb) {...} 

};