How to Encrypt Passwords in Node.js and Store Them in a Database

How to Encrypt Passwords in Node.js and Store Them in a Database
In the world of web development, security is paramount. One critical aspect of securing a web application is ensuring that user passwords are properly encrypted before being stored in the database. In this blog post, we’ll walk you through how to encrypt passwords in Node.js using bcryptjs and store them securely in a database.
Why Encrypt Passwords?
Storing passwords in plain text is a significant security risk. If your database is compromised, all user passwords will be exposed. Encrypting passwords ensures that even if your database is breached, the attackers will not have access to the actual passwords.
Getting Started
First, ensure you have Node.js installed on your machine. If you don’t have it yet, you can download it from here.
Next, create a new Node.js project or navigate to your existing project directory and run the following command to install the bcryptjs library:
npm install bcryptjsSetting Up the Registration Route
Let’s set up an Express route to handle user registration. In this route, we will encrypt the user’s password before saving it to the database. Here’s the complete code for the registration route:
const express = require('express');
const bcrypt = require('bcryptjs');
const moment = require('moment');
const blogDB = require('./db'); // Assume this is your database connection
const router = express.Router();
const saltRounds = 10;
router.post('/register', async (req, res) => {
try {
const { username, mobile, email, password } = req.body;
// Encrypt the password
const hash = bcrypt.hashSync(password, saltRounds);
// Check if the mobile number or email already exists
let result = await blogDB.query(
'SELECT * FROM users WHERE log_mobile_no = :mobile OR log_email_address = :email',
{
replacements: { mobile, email },
type: blogDB.QueryTypes.SELECT,
}
);
if (result.length > 0) {
return res.json({
status: 'error',
message: 'Mobile number or email already exists',
code: '500',
});
}
// Validate mobile number length and email
if (mobile.length !== 10 ) {
return res.json({
status: 'error',
message: 'Mobile number length should be 10',
code: '500',
});
}
// Insert the new user into the database
const stmt = await blogDB.query(
'INSERT INTO users (log_full_name, log_mobile_no, log_email_address, log_password, log_insert_dt) VALUES (:name, :mobile, :email, :password, :dt)',
{
replacements: {
name: username,
mobile,
email,
password: hash,
dt: moment().format('YYYY-MM-DD HH:mm:ss'),
},
type: blogDB.QueryTypes.INSERT,
}
);
if(stmt.length>0)
{
return res.json({ status: 'success', message: 'User registered successfully' });
}
else
{
return res.json({ status: 'error', message: 'Something Went Wrong!Please try again later.' });
}
} catch (error) {
console.error('Error', error);
return res.json({ status: 'error', message: 'Failed to register user' });
}
});
module.exports = router;Breakdown of the Code
- Dependencies: We import the necessary modules including
express,bcryptjs,moment, and our hypotheticalblogDBmodules. - Encryption: We use
bcrypt.hashSyncto encrypt the user’s password. ThesaltRoundsvariable determines the cost factor of the encryption, making it more secure by increasing the time required to encrypt the password. - Uniqueness Check: We check if the mobile number or email already exists in the database to avoid duplicates.
- Validation: We validate that the mobile number is exactly 10 digits.
- Database Insertion: We insert the new user’s details into the database, including the encrypted password and the current timestamp.
Conclusion
Encrypting passwords is a crucial step in securing user data in any web application. By following the steps outlined above, you can ensure that user passwords are stored securely in your database. Always remember to validate and sanitize user inputs to further enhance the security of your application.
Happy coding!