Section 31 – Lesson 402 – Complete 2020 Web Development Bootcamp

Lesson 402 – Level 3 Hashing Passwords

Hashing removes the need for an encryption key.

When a user registers on your site using a password, a hash function turns that password into a hash which is stored in your database.

When that user later logs in using his password, the password typed in by the user in the login form is then turned into a hash using the hash function and that hash is compared to the hash already stored in the database to confirm that there is a match.

The first step to implementing hashing in our project is to install the npm md5 package by typing this code in the terminal –

npm i md5

In the app.js file you then require md5 using this code –

const md5 = require("md5");

You then refactor the constant variable newUser in the app.post(“/register”) route to call md5 on the password. This is the refactored code –

app.post("/register", function(req, res) {

	const newUser = new User({
		email: req.body.username,
		password: md5(req.body.password)

	});

	newUser.save(function(err) {
		if (err) {
			console.log(err);
		} else {
			res.render("secrets");
		}
	});

});

In order to be able to compare a password input on the login form with a stored password involves refactoring the app.post(“/login”) route to call md5 on the input password. This is the refactored code –

app.post("/login", function(req, res) {
	const username = req.body.username;
	const password = md5(req.body.password);

	User.findOne({email: username}, function(err, foundUser) {
		if (err) {
			console.log(err);
		} else {
			if (foundUser) {
				if (foundUser.password === password) {
					res.render("secrets");
				} 
			}
		}
	});
});