The next step is to make sure that the user's password will be encrypted when we store it on MongoDB. This process is really easy and only uses a new library, called bcrypt .
bcrypt is available at https://www.npmjs.com/package/bcrypt.
To use bcrypt, install it through npm:
$ npm install --save bcrypt
You also need to install the types:
$ npm install --save @types/bcrypt
Once you have installed bcrypt, as well as its types, change the 02_user.spec.ts file to create a new user on the before step, with the password encrypted:
...
import * as bcrypt from 'bcrypt'
...
before(async () => {
expect(UserModel.modelName).to.be.equal('User')
UserModel.collection.drop()
const newUser = new UserModel(user)
newUser.password = bcrypt.hashSync(newUser.password, 10)
await newUser.save((error, userCreated) => {
user._id = userCreated._id
})
})
newUser.password = bcrypt.hashSync(newUser.password, 10) will encrypt the password before storing it in the database. After that, change the addUser method on the user controller so that the password is encrypted before it is saved:
...
import * as bcrypt from 'bcrypt'
...
export let addUser = (req: Request, res: Response, next: NextFunction) => {
const newUser = new UserModel(req.body)
newUser.password = bcrypt.hashSync(newUser.password, 10)
newUser.save((error, user) => {
user = halson(user.toJSON()).addLink('self', `/users/${user._id}`)
return formatOutput(res, user, 201, 'user')
})
}
You may have noticed that, on MongoDB, the password is now encrypted, as shown in the following screenshot:
Password encrypted on MongoDB