Woodshop
Search…
Hash a password with bcrypt
This example shows you how to use bcrypt to convert a password field into unreadable strings of characters.

Requirements

    An admin backend running on forest-express-sequelize
    bcrypt npm package

How it works

Directory: /models

This directory contains the users.js file where the model is declared.
In this example, we're using a custom setter for the password attribute of the users models.
/models/users.js
1
const bcrypt = require('bcrypt');
2
3
module.exports = (sequelize, DataTypes) => {
4
const { Sequelize } = sequelize;
5
6
const Users = sequelize.define('users', {
7
email: {
8
type: DataTypes.STRING,
9
},
10
password: {
11
type: DataTypes.STRING,
12
allowNull: true,
13
// Storing passwords in plaintext in the database is terrible.
14
// Hashing the value with an appropriate cryptographic hash function is better.
15
set(value) {
16
const hash = bcrypt.hashSync(value, 10);
17
this.setDataValue('password', hash);
18
},
19
},
20
}, {
21
tableName: 'users',
22
timestamps: false,
23
schema: process.env.DATABASE_SCHEMA,
24
});
Copied!
The above example involving password handling, although much better than simply storing the password in plaintext, are far from perfect security. Handling passwords properly is hard, everything here is just for the sake of an example to show Sequelize functionality.
Last modified 1yr ago