In my last tutorial, I had explained how to register users and authenticate a user with their password without using any encryption layer but that was not good practice to store password in the table.
In this tutorial, I will tell you how to use basic encryption layer to store password using bcrypt
module in Node.js
This is the proper way to save password in the database using bcrypt
module.
There are 2 ways to hash the password - sync and async by using the bcrypt module.
Make sure you are using a stable version of node because the module does not support unstable versions.
To use the bcrypt module in Node.js, install it via NPM.
$ npm install bcrypt --save
Once you have installed the bcrypt module, include it in your node application.
// require the bcrypt module var bcrypt = require('bcrypt');Synchronous Usase
First generate the salt and then hash the password with the salt.
var salt = bcrypt.genSaltSync(10); var hash = bcrypt.hashSync(req.body.password, salt); -- OR -- var hash = bcrypt.hashSync(req.body.password, 10);
To authenticate the incoming password string with the hash stored in the database :
bcrypt.compareSync(req.body.password, hash);
If requested password match with the hash password then compareSync
will return true
.
You can go with Asynchronous
method in following way :
bcrypt.hash(req.body.password, 10, function(err, hash) { // Store hash password in your Database. });
To compare the requested password with database password, you can use following line of code :
bcrypt.compare(req.body.password, hash, function(err, res) { // res == true });
A complete example to authenticate password from hash password :
- module.exports.authenticate=function(req,res){
- var email=req.body.email;
- var password=req.body.password;
- connection.query('SELECT * FROM users WHERE email = ?',[email], function (error, results, fields) {
- if (error) {
- res.json({
- status:false,
- message:'there are some error with query'
- })
- }else{
- if(results.length >0){
- bcrypt.compare(password, results[0].password, function(err, ress) {
- if(!ress){
- res.json({
- status:false,
- message:"Email and password does not match"
- });
- }else{
- res.json({
- status:true,
- message:"Successfully Login"
- })
- }
- });
- }
- else{
- res.json({
- status:false,
- message:"Email does not exits"
- });
- }
- }
- });
- }