Last active
April 1, 2022 15:40
-
-
Save Andaeiii/9197b32f3870158c170c9add305c73c0 to your computer and use it in GitHub Desktop.
using bcrypt to encrypt password in nodejs/express applications using moongoose...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//npm install bcrypt --save | |
import bcrypt from 'bcryptjs'; | |
import UserModel from '../models/users.js'; | |
export default config = { | |
PORT: 5200, | |
DB_USER: '.......', | |
DB_PASS: '.......', | |
DB_NAME: '.......', | |
SALT_ROUNDS: 10 | |
}; | |
var salt = bcrypt.genSaltSync(config.SALT_ROUNDS); | |
export const createUser = async (req, res) => { | |
const user = req.body; | |
const hashed = bcrypt.hashSync(user.password, salt); //hash password here.... | |
const userObj = { ...user, password: hashed }; | |
...... | |
}; | |
//controller function to validate and check password.. using bcrypt. | |
export const loginUser = async (req, res) => { | |
const user = req.body; | |
try { | |
const userObj = await UserModel.findOne({ email: user.email }).exec(); | |
if (!mongoose.Types.ObjectId.isValid(userObj._id)) return res.status(404).send('user does not exist'); //check for valid ids... | |
const result = bcrypt.compareSync(user.password, userObj.password) == true ? TRUE : FALSE; | |
..... | |
} catch (error) { | |
res.status(409).json({ message: error.message }) | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment