Hashing and check password with Bcrypt in Node.js

Bcrypt is a native module for Node.js.  Passwords have a big role in keeping datas secure. Hashing passwords are simple solutions to keep it secure but it's not good enough. Bcrypt is a solution for password encryption. It uses BCrypt hashing to encrypt your passwords. It was designed by Niels Provos and David Mazieres. It’s based on the cryptomatic algorithm Blowfish block cipher. BCrypt uses a key factor to adjust the cost of hashing. With the changes hash output can be influenced. 


Installing BCrypt


$ npm install bcryptjs
Make an authentication class that can accommodate the functions for logging in and password checking. In our example I’m using Typescript.
import * as bcrypt from 'bcryptjs';

export default class Auth {

    public static hashPassword(password: string, rounds: number, callback: (error: Error, hash: string) => void) : void {
        bcrypt.hash(password, rounds, (error, hash) => {
            callback(error, hash);
        });
    }
}
In another Class without instantiating the class we use this. The callback can receive two parameters error, a valid hash.
import Auth from './../utils/auth';

export default class SomeClass {

    public myFnct() {
        Auth.hashPassword('myPassword', 12, (err, hash) => {
            if(err) {
                // throw and error
            } else {
                // store the new hash in the database etc
            }
        });
    }
}
Hashing Salts are automatically stored in hash so there is no need for creating a field for storing hash in your database. In the Authentication class we have already created, create a public static method.
public static compare(password: string, dbHash: string, callback: (error: string | null, match: boolean | null) => void) {
    bcrypt.compare(password, dbHash, (err: Error, match: boolean) => {
        if(match) {
            // passwords match
            callback(null, true);
        } else {
            // passwords do not match
            callback('Invalid password match', null);
        }
    });
}
After fetching this from db we will call this method. In our example we have a login method that takes email and password as input. User’s data is selected from a database using email. Then we will take the password entered by the user and the password from the database and pass both to compare methods in our Authentication class. The resulting callback will tell you if it's matching or not. Callback is used here to accept incoming requests to web service while CPU time is being shared.