Registration
In the user registration process, we have to apply the password hasheado before storing it in the database. To do this, we use the bcrypt library to calculate the hash associated with the password. The library will use the value we pass to it as saltRounds to apply the processing cost to generate the hash.
var bodyParser = require('body-parser');
var bcrypt = require('bcrypt');
var usersDB = require('usersDB');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
var BCRYPT_SALT_ROUNDS = 12;
app.post('/register', function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
bcrypt.hash(password, BCRYPT_SALT_ROUNDS)
.then(function(hashedPassword) {
return usersDB.saveUser(username, hashedPassword);
})
.then(function() {
res.send();
})
.catch(function(error){
console.log("Error saving user: ");
console.log(error);
next();
});
});
Authentication
When a user logs into our system, we need to check that the password entered is correct. Unlike other systems that would decrypt the password in the database (if it is encrypted), and compare it with the one entered by the user, what we do with bcrypt is encrypt the one entered by the user. To do this, we will pass the password to bcrypt to calculate the hash, but also the password stored in the database associated with the user (hash). This is because, as mentioned before, the bcrypt algorithm used a random segment (salt) to generate the hash associated with the pasword. This was stored along with the password, and you need it to recalculate the hash of the password entered by the user and finally compare with the one entered when registering and see if they match.
The response of the call to the library will be a boolean that indicates whether the comparison is correct or not, and according to this value we will give the user for authenticated or not.
app.post('/login', function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
usersDB.getUserByUsername(username)
.then(function(user) {
return bcrypt.compare(password, user.password);
})
.then(function(samePassword) {
if(!samePassword) {
res.status(403).send();
}
res.send();
})
.catch(function(error){
console.log("Error authenticating user: ");
console.log(error);
next();
});
});