From df666dd2140c8955765972230260d6e4bd5de42a Mon Sep 17 00:00:00 2001 From: Claudius Date: Mon, 13 May 2019 10:55:37 +0200 Subject: getting password hashing into a hook where it could be async Signed-off-by: Claudius --- lib/models/user.js | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) (limited to 'lib/models') diff --git a/lib/models/user.js b/lib/models/user.js index 648db73e..bcf3c094 100644 --- a/lib/models/user.js +++ b/lib/models/user.js @@ -5,7 +5,7 @@ var scrypt = require('@mlink/scrypt') // core var logger = require('../logger') -var {generateAvatarURL} = require('../letter-avatars') +var { generateAvatarURL } = require('../letter-avatars') module.exports = function (sequelize, DataTypes) { var User = sequelize.define('User', { @@ -41,11 +41,7 @@ module.exports = function (sequelize, DataTypes) { } }, password: { - type: Sequelize.TEXT, - set: function (value) { - var hash = scrypt.kdfSync(value, scrypt.paramsSync(0.1)).toString('hex') - this.setDataValue('password', hash) - } + type: Sequelize.TEXT } }, { instanceMethods: { @@ -153,5 +149,17 @@ module.exports = function (sequelize, DataTypes) { } }) + function updatePasswordHashHook (user, options, done) { + // suggested way to hash passwords to be able to do this asynchronously: + // @see https://github.com/sequelize/sequelize/issues/1821#issuecomment-44265819 + if (!user.changed('password')) { return done() } + const hash = scrypt.kdfSync(user.get('password'), scrypt.paramsSync(0.1)).toString('hex') + user.setDataValue('password', hash) + done() + } + + User.beforeCreate(updatePasswordHashHook) + User.beforeUpdate(updatePasswordHashHook) + return User } -- cgit v1.2.3