bcrypt nodejs example
Example 1: how to hash password in node js
npm i bcrypt
const bcrypt = require('bcrypt');
async function hashIt(password){
const salt = await bcrypt.genSalt(6);
const hashed = await bcrypt.hash(password, salt);
}
hashIt(password);
// compare the password user entered with hashed pass.
async function compareIt(password){
const validPassword = await bcrypt.compare(password, hashedPassword);
}
compareIt(password);
Example 2: npm bcrypt
npm install bcrypt
Example 3: bcryptjs
npm i bcryptjs
yarn add bcryptjs
Example 4: formidable nodejs example
// make this a middleware function,
// then put it on the route like you used jwt,
// then get the value with req.users.
const { IncomingForm } = require('formidable')
const { resolve } = require('path')
const { existsSync, writeFileSync } = require('fs')
module.exports = (req, res, next) => {
const form = new IncomingForm({
maxFileSize: 1 * 1024 * 1024,
keepExtensions: true
})
form.parse(req, (error, fields, file) => {
if (error) return next(error)
const patternFile = /\.(jpg|jpeg|png|svg|gif|raw|webp)$/gi.test(file.productImage.name)
if (patternFile) {
const pathFile = resolve(process.cwd(), 'servers/uploads/', file.productImage.name)
const fileExits = existsSync(pathFile)
if (!fileExits) {
writeFileSync(pathFile)
req.users = JSON.parse(JSON.stringify({ fields, file }))
return next()
}
req.users = JSON.parse(JSON.stringify({ fields, file }))
return next()
}
})
}
Example 5: bcrypt compare hash and password
var bcrypt = dcodeIO.bcrypt;
/** One way, can't decrypt but can compare */
var salt = bcrypt.genSaltSync(10);
/** Encrypt password */
bcrypt.hash('anypassword', salt, (err, res) => {
console.log('hash', res)
hash = res
compare(hash)
});
/** Compare stored password with new encrypted password */
function compare(encrypted) {
bcrypt.compare('aboveusedpassword', encrypted, (err, res) => {
// res == true or res == false
console.log('Compared result', res, hash)
})
}
// If u want do the same with NodeJS use this:
/* var bcrypt = require('bcryptjs') */