1. Learn about hashing in NodeJS
  2. Learn about salting
  3. Salt and hash password using bcrypt
  4. Compare the password with the hash
npm init -y
npm init express bcrypt --save
{
"name": "auth",
"version": "1.0.0",
"description": "",
"scripts": {
"devStart":"nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.1",
"express": "^4.17.3"
},
"devDependencies": {
"nodemon": "^2.0.15"
}
}
const express = require('express');
const app = express();

app.listen(3000);
let users = []; // store user details in an arrayapp.get('/users', (req, res) => {
res.json(users)
});
app.use(express.json());app.post('/user/register', async (req, res) => {
try {
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(req.body.password, salt);
users.push({username: req.body.username, password: passwordHash});
res.json(users);
} catch (e) {
res.status(500).send(e.toString());
}
});
app.post('/user/login', async (req, res) => {
try {
const user = users.find(user => user.username === req.body.username);
console.log(user);
if (!user) {
res.status(400).send('User Not Found!');
}
if (await bcrypt.compare(req.body.password, user.password)) {
res.send('LoggedIn');
} else {
res.send('Not Valid User!');
}
} catch (e) {
console.log(e.toString());
}
})
const express = require('express');
const bcrypt = require('bcrypt');
const app = express();

let users = [];
app.use(express.json());

app.post('/user/register', async (req, res) => {
try {
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(req.body.password, salt);
users.push({username: req.body.username, password: passwordHash});
res.json(users);
} catch (e) {
res.status(500).send(e.toString());
}
});

app.post('/user/login', async (req, res) => {
try {
const user = users.find(user => user.username = req.body.username);
console.log(user);
if (!user) {
res.status(400).send('User Not Found!');
}
if (await bcrypt.compare(req.body.password, user.password)) {
res.send('LoggedIn');
} else {
res.send('Not Valid User!');
}
} catch (e) {
console.log(e.toString());
}
})

app.listen(3000);