Reputation: 165
I got the below codes from the post https://medium.com/@benjaminpwagner/using-sequelize-hooks-and-crypto-to-encrypt-user-passwords-5cf1a27513d9. But
const Sequelize = require('sequelize')
const crypto = require('crypto')
const db = require('./db.js')
const User = db.define('user', {
email: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: Sequelize.STRING,
get() {
return () => this.getDataValue('password')
}
},
salt: {
type: Sequelize.STRING,
get() {
return() => this.getDataValue('salt')
}
}
})
#FUNCTIONS UNDER USER CLASS
User.generateSalt = function() {
return crypto.randomBytes(16).toString('base64')
}
User.encryptPassword = function(plainText, salt) {
return crypto
.createHash('RSA-SHA256')
.update(plainText)
.update(salt)
.digest('hex')
}
const setSaltAndPassword = user => {
if (user.changed('password')) {
user.salt = User.generateSalt()
user.password = User.encryptPassword(user.password(), user.salt())
}
}
User.beforeCreate(setSaltAndPassword)
User.beforeUpdate(setSaltAndPassword)
What this.getDataValue('password') does?
Upvotes: 0
Views: 125
Reputation: 22758
getDataValue
is to get the underlying value because using this.password
instead of getDataValue('password')
in the password's getter will lead to infinite recursion: the getter will call itself.
See getDataValue in the official documentation.
Upvotes: 1