3

I'm using sequelize at first time and have a question about encrypt user password.

I want use the function AES_ENCRYPT to encrypt a string text. My question is, how can I call that function on sequelize??

2 Answers 2

5

All you need is bcrypt package and hook beforeCreate ,

What it will do is before inserting entry to DB will check passowrd field and encrypt is before insert into DB

Here you go (Snippet for password encrypt) :

const bcrypt = require('bcrypt');

var User = db.sequelize.define( 'user' , {
    ...
    password : {
        type : db.Sequelize.STRING
    },
    ...
},
{
    hooks : {
        beforeCreate : (user , options) => {
            {
                user.password = user.password && user.password != "" ? bcrypt.hashSync(user.password, 10) : "";
            }
        }
    }
});
Sign up to request clarification or add additional context in comments.

6 Comments

There is not another way without external packages?
@Raugaral , this packages is most popular for encryption, so dont worry about it , you wont regret on this.
Writing your own encryption is a bad idea, encryption is incredibly sophisticated and it's easy to make costly mistakes. bcrypt is a popular library so it's secure and works well!
You can't decrypt if you have encrypted with bcrypt. @KieranQuinn
@KieranQuinn , you can use crypto js and use other encryption method so that you can decrypt it back , like AES. npmjs.com/package/crypto-js
|
3

You nedd bcrypt and hooks : beforeCreate and beforeUpdate.

const User = sequelize.define('User', {
...
    password: {
        type: DataTypes.STRING,
        allowNull: false,
    }
...
});

function generateHash(user) {
    if (user === null) {
        throw new Error('No found employee');
    }
    else if (!user.changed('password')) return user.password;
    else {
        let salt = bcrypt.genSaltSync();
        return user.password = bcrypt.hashSync(user.password, salt);
    }
}

User.beforeCreate(generateHash);

User.beforeUpdate(generateHash);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.